import { taskEntity } from "@/drizzle/model/taskEntity";
import { useColor } from "@/hooks/color";
import { useLoadedFontFamilyByAction } from "@/hooks/font";
import { useUpdateForm } from "@/hooks/task.form";
import { AppDispatch, RootState } from "@/stores";
import { listTaskItem, TaskSelect } from "@/stores/tasks/item";
import { eq } from "drizzle-orm";
import { router } from "expo-router";
import React from "react";
import { Card, Checkbox, Colors, Text, View } from "react-native-ui-lib";
import { useDispatch, useSelector } from "react-redux";

const TasksShowItems: React.FC<{ item: TaskSelect }> = ({ item }) => {
  const action = useDispatch<AppDispatch>();
  const timer = useSelector<RootState, Slice.IItemTaskTimerSlice>(state => state.timer);
  const color = useColor();
  const [clickTimer, setClickTimer] = React.useState(0);
  const handleDoublePress = () => {
    router.navigate({ pathname: "/(modal)/addTask", params: { type: "2009", item: JSON.stringify(item) } });
  };

  const handlePress = () => {
    const now = Date.now();
    if (now - clickTimer < 300) {
      handleDoublePress();
    }
    setClickTimer(now);
  };
  const updatedTask = async (item: TaskSelect) => {
    const result = await useUpdateForm
      .set({
        status: !item.status,
      })
      .where(eq(taskEntity.id, item.id))
      .execute();
    if (result.changes > 0) action(listTaskItem(timer));
  };
  return (
    <Card className='flex p-3 my-2 mx-2' elevation={20} backgroundColor={color.colors.background} onPress={handlePress}>
      <View className='flex flex-row items-center gap-2 justify-start w-full'>
        <Checkbox
          value={item.status}
          onValueChange={_value => updatedTask({ ...item })}
          color={Colors.getColorTint(color.colors.primary, item.status ? 70 : 40)}
        />
        <View className='flex grow'>
          <Text
            numberOfLines={1}
            ellipsizeMode='tail'
            style={{
              color: Colors.getColorTint(color.colors.text, item.status ? 70 : 40),
              textDecorationLine: item.status ? "line-through" : "none",
              ...useLoadedFontFamilyByAction("CHARACTER_SOUL"),
            }}
            text60>
            {item.title}
          </Text>
        </View>
      </View>
    </Card>
  );
};

export default TasksShowItems;
